<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>发表评论</title>
    <script src="../lib/vue-2.4.0.js"></script>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7.css">
</head>
<body>
    <div id="app">

        <cmt-box @func="loadComments"></cmt-box>

        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" :key="item.id">
                <span class="badge">评论人: {{item.user}}</span>
                {{ item.content }}
            </li>
        </ul>
    </div>

    <template id="tm1">
        <div>
            <div class="form-group">
                <label>评论人：</label>
                <input type="text" class="form-control" v-model="user">
            </div>

            <div class="form-group">
                <label>评论内容：</label>
                <textarea class="form-control" v-model="content"></textarea>
            </div>

            <div class="form-group">
                <input type="button" value="发表评论" class="btn btn-primary" @click="postComment">
            </div>
        </div>
    </template>

    <script>

        // 需要使用父组件的数据变量
        var commentBox = {
            template: "#tm1",
            data() {
                return {
                    user: '',
                    content: ''
                }
            },
            methods: {
                postComment() {
                    var comment = { id: Date.now(), user: this.user, content: this.content }

                    // 从 localStorage 中获取所有的评论
                    var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                    list.unshift(comment)
                    // 重新保存最新的 评论数据
                    localStorage.setItem('cmts', JSON.stringify(list))

                    this.user = this.content = ''

                    // this.loadComments() // ?????
                    this.$emit('func')
                }
            }
        }


        var vm = new Vue({
            el: "#app",
            data: {
                list: [
                    {id: Date.now(), user: '李白', content: "天生我材必有用"},
                    {id: Date.now(), user: '江小白', content: "劝君更尽一杯酒"},
                    {id: Date.now(), user: '小马', content: "我姓马,风吹草地见牛羊的马"}
                ]
            },
            components : {
                'cmt-box': commentBox
            },
            created: function () {
                this.loadComments()
            },
            methods: {
                loadComments() { // 从本地的 localStorage 中，加载评论列表
                    var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                    this.list = list
                }
            },
        })
    </script>
</body>
</html>